package com.esfak47.mediafetcher.app.service.impl;

import com.esfak47.common.digest.DigestUtils;
import com.esfak47.common.extension.URL;
import com.esfak47.common.job.Job;
import com.esfak47.common.job.impl.CompletableJob;
import com.esfak47.common.lang.Inject;
import com.esfak47.common.utils.StringUtils;
import com.esfak47.mediafetcher.core.constants.Constants;
import com.esfak47.mediafetcher.core.domain.DefaultFetchAble;
import com.esfak47.mediafetcher.core.domain.Media;
import com.esfak47.mediafetcher.core.event.Event;
import com.esfak47.mediafetcher.core.event.EventGroupEnum;
import com.esfak47.mediafetcher.core.event.EventSender;
import com.esfak47.mediafetcher.core.service.CrawlerService;
import com.esfak47.mediafetcher.core.service.JobBuilder;

import java.util.Optional;
import java.util.UUID;

/**
 * @author tony
 * @date 2018/5/6
 */
public class MediaCrawlerJobBuilder implements JobBuilder {
    @Inject
    private CrawlerService crawlerService;
    @Inject
    private EventSender eventSender;

    @Override
    public Job createJob(URL url) {
        String webUrl = url.getParameter("url");
        String type = url.getParameter("ptype");
        if (StringUtils.isBlank(webUrl)) {
            return null;
        }
        String mediaId = DigestUtils.sha1Hex(webUrl);

        final String id = UUID.randomUUID().toString();
        return CompletableJob.create("抓取视频", id, completableJob1 -> {
            Optional<Media> videoExtInfo = crawlerService.getVideoExtInfo(new DefaultFetchAble(type, webUrl));
            videoExtInfo.ifPresent(media -> {
                media.setId(mediaId);
                eventSender.send(new Event(EventGroupEnum.MEDIA,
                    Constants.MediaSubjects.fetched.name(), media));
            });
        });
    }
}
